package com.zero.manage.web.utils.dynamicsource.processor;

import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.zero.manage.web.utils.dynamicsource.DynamicSourceUtil;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class ZeroExpressionProcessor extends DsProcessor {
    @Autowired
    private DynamicSourceUtil dynamicSourceUtil;
    private static final ParameterNameDiscoverer NAME_DISCOVERER = new DefaultParameterNameDiscoverer();
    private static final ExpressionParser PARSER = new SpelExpressionParser();
    private ParserContext parserContext = new ParserContext() {
        @Override
        public boolean isTemplate() {
            return false;
        }

        @Override
        public String getExpressionPrefix() {
            return null;
        }

        @Override
        public String getExpressionSuffix() {
            return null;
        }
    };

    public ZeroExpressionProcessor() {
    }

    @Override
    public boolean matches(String key) {
        return true;
    }

    @Override
    public String doDetermineDatasource(MethodInvocation invocation, String key) {
        Method method = invocation.getMethod();
        Object[] arguments = invocation.getArguments();
        EvaluationContext context = new MethodBasedEvaluationContext(null, method, arguments, NAME_DISCOVERER);
        Object value = PARSER.parseExpression(key, this.parserContext).getValue(context);
        String s = value == null ? null : value.toString();
        dynamicSourceUtil.addSource(s);
        return s;
    }

    public void setParserContext(ParserContext parserContext) {
        this.parserContext = parserContext;
    }
}
